package com.zhuge_new.Fragment;


import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.bumptech.glide.Glide;
import com.flyco.animation.BaseAnimatorSet;
import com.flyco.animation.BounceEnter.BounceTopEnter;
import com.flyco.animation.FadeExit.FadeExit;
import com.flyco.animation.FlipEnter.FlipVerticalSwingEnter;
import com.flyco.animation.SlideExit.SlideBottomExit;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.MaterialDialog;
import com.flyco.dialog.widget.NormalDialog;
import com.gongwen.marqueen.SimpleMF;
import com.gongwen.marqueen.SimpleMarqueeView;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.maning.mndialoglibrary.MToast;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.xuezj.cardbanner.CardBanner;
import com.xuezj.cardbanner.adapter.BannerAdapter;
import com.xuezj.cardbanner.adapter.BannerViewHolder;
import com.xuezj.cardbanner.view.RoundedImageView;
import com.zhuge_new.Activity.CreditManageActivity;
import com.zhuge_new.Activity.CreditAddition1Activity;
import com.zhuge_new.Activity.CreditCardActivity;
import com.zhuge_new.Activity.RealNameActivity;
import com.zhuge_new.Activity.ShareActivity;
import com.zhuge_new.Base.BaseFragment;
import com.zhuge_new.Activity.MerchantHiredActivity;
import com.zhuge_new.R;
import com.zhuge_new.Activity.WebActivity;
import com.zhuge_new.bean.BannerBean;
import com.zhuge_new.bean.WalkTextBean;
import com.zhuge_new.http.StringDialogCallback;
import com.zhuge_new.share.BaseHttp;
import com.zhuge_new.untils.DataParse;
import com.zhuge_new.untils.PreferencesUtils;
import com.zhuge_new.wxapi.Constacts;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;

/**
 * Created by lenovo on 2018-08-27.
 */

public class HomeFragment extends BaseFragment implements View.OnClickListener {


    BaseAnimatorSet bas_in = new FlipVerticalSwingEnter();
    BaseAnimatorSet bas_out = new FadeExit();
    private ArrayList listbanner=new ArrayList();
    private View view;
    private IWXAPI wxApi;
    private CardBanner home_banner;
    private ImageView home_phone;
    private LinearLayout home_make_money,home_loan_supermarket,home_safety,home_Merchant_hired;
    private LinearLayout home_credit_manage,home_apply_for,home_contributing,home_credits_exchange;
    private String url;
    private List<String> datas=new ArrayList<>();
    private SimpleMarqueeView walktext;
    private SimpleMF<String> marquessFactory;
    private String savings="false";

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_home_page, container, false);
        return view;

    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        init_title();
        getData();
        walktext();
        getSavings();
    }

    @Override
    public void init_title() {
        super.init_title();
        wxApi = WXAPIFactory.createWXAPI(getActivity(), Constacts.WXAPPID);
        wxApi.registerApp(Constacts.WXAPPID);
        home_banner = getActivity().findViewById(R.id.home_banner);
        home_phone = getActivity().findViewById(R.id.home_phone);
        home_make_money = getActivity().findViewById(R.id.home_make_money);
        home_credit_manage = getActivity().findViewById(R.id.home_credit_manage);
        home_apply_for=getActivity().findViewById(R.id.home_apply_for);
        home_contributing=getActivity().findViewById(R.id.home_contributing);
        home_credits_exchange=getActivity().findViewById(R.id.home_credits_exchange);
        home_loan_supermarket=getActivity().findViewById(R.id.home_loan_supermarket);
        home_safety=getActivity().findViewById(R.id.home_safety);
        walktext = getActivity().findViewById(R.id.walktext);
        home_Merchant_hired=getActivity().findViewById(R.id.home_Merchant_hired);
        marquessFactory = new SimpleMF(getActivity());
        home_phone.setOnClickListener(this);
        home_contributing.setOnClickListener(this);
        home_make_money.setOnClickListener(this);
        home_credit_manage.setOnClickListener(this);
        home_apply_for.setOnClickListener(this);
        home_safety.setOnClickListener(this);
        home_credits_exchange.setOnClickListener(this);
        home_loan_supermarket.setOnClickListener(this);
        home_safety.setOnClickListener(this);
        home_Merchant_hired.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.home_phone:
                phone_dialog();
                break;
            case R.id.home_make_money:
                Intent intent=new Intent(getActivity(),ShareActivity.class);
                startActivity(intent);
                break;
            case R.id.home_contributing:
                MToast.makeTextShort(getActivity(),"努力开发中，敬请期待").show();
                break;
            case R.id.home_credits_exchange:
                MToast.makeTextShort(getActivity(),"努力开发中，敬请期待").show();
                break;
            case R.id.home_loan_supermarket:
                MToast.makeTextShort(getActivity(),"努力开发中，敬请期待").show();
                realname_dialog();
                break;
            case R.id.home_safety:
                Intent safety=new Intent(getActivity(), WebActivity.class);
                safety.putExtra("title","安全保障");
                safety.putExtra("url", url);
                startActivity(safety);
                break;
            case R.id.home_credit_manage:
                if ("1".equals(PreferencesUtils.getString(getActivity(),"isPass"))){
                    Intent intent1=new Intent(getActivity(),CreditManageActivity.class);
                    startActivity(intent1);
                }else if ("0".equals(PreferencesUtils.getString(getActivity(),"isPass"))){
                    MToast.makeTextShort(getActivity(),"实名认证正在审核，请稍等").show();
                }else if ("-1".equals(PreferencesUtils.getString(getActivity(),"isPass"))){
                    MToast.makeTextShort(getActivity(),"实名认证未通过，请联系客服").show();
                }else {
                    realname_dialog();
                }
                break;
            case R.id.home_apply_for:
                if ("1".equals(PreferencesUtils.getString(getActivity(),"isPass"))){
                    Intent intent1=new Intent(getActivity(),WebActivity.class);
                    intent1.putExtra("title","在线办卡");
                    intent1.putExtra("url","http://www.qichangkeji.vip/gongzhonghaoWeb/page/downCard.html?userId=5689");
                    startActivity(intent1);
                }else if ("0".equals(PreferencesUtils.getString(getActivity(),"isPass"))){
                    MToast.makeTextShort(getActivity(),"实名认证正在审核，无法进行在线办卡").show();
                }else if ("-1".equals(PreferencesUtils.getString(getActivity(),"isPass"))){
                    MToast.makeTextShort(getActivity(),"实名认证未通过，无法进行在线办卡").show();
                }else {
                    realname_dialog();
                }
                break;
            case R.id.home_Merchant_hired:
                Intent intent2=new Intent(getActivity(),MerchantHiredActivity.class);
                startActivity(intent2);
                break;
        }
    }

    @Override
    public void getData() {
        super.getData();
        OkGo.<String>post(BaseHttp.get_small)
                .tag(this)
                .headers("token", PreferencesUtils.getString(getActivity(),"token"))
                .execute(new StringDialogCallback(getActivity()) {
                    @Override
                    public void onSuccessResponse(Response<String> response, String msg, String msgCode) {
                        BannerBean bannerBean= (BannerBean) new DataParse().getBean(response.body(),BannerBean.class,0);
                        for (int i=0;i<bannerBean.getSmall().size();i++){
                            listbanner.add(BaseHttp.baseImg1+bannerBean.getSmall().get(i).getSliderImg());
                        }
                        home_banner.setBannerAdapter(new BannerAdapter() {
                            @Override
                            public int getCount() {
                                return listbanner.size();
                            }

                            @Override
                            public BannerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                                View view=View.inflate(getActivity(),R.layout.item_home_item,null);
                                ViewHolder viewHolder=new ViewHolder(view);
                                return viewHolder;
                            }

                            @Override
                            public void onBindViewHolder(BannerViewHolder holder, int position) {
                                ViewHolder viewHolder = (ViewHolder) holder;
                                Glide.with(getActivity())
                                        .load(listbanner.get(position))
                                        .into(viewHolder.roundedImageView);
                            }
                        });
                        home_banner.start();
                        home_banner.setOnItemClickListener(new CardBanner.OnItemClickListener() {
                            @Override
                            public void onItem(int position) {
                                //点击事件
                            }
                        });
                    }
                });
        OkGo.<String>post(BaseHttp.get_safebusiness)
                .tag(getActivity())
                .execute(new StringDialogCallback(getActivity()) {
                    @Override
                    public void onSuccessResponse(Response<String> response, String msg, String msgCode) {
                        try {
                            JSONObject obj=new JSONObject(response.body());
                            url=obj.getString("safebusinessUrl");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    //实名认证对话框
    private void realname_dialog() {
        final MaterialDialog dialog = new MaterialDialog(getContext());
        dialog.btnNum(1)
                .content("您还没有进行实名认证，是否现在去认证？")//
                .btnText("去认证")//
                .showAnim(bas_in)//
                .dismissAnim(bas_out)//
                .show();
        dialog.setOnBtnClickL(
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        Intent intent=new Intent(getActivity(),RealNameActivity.class);
                        startActivity(intent);
                        dialog.dismiss();
                    }
                });
    }


    class ViewHolder extends BannerViewHolder {
        public RoundedImageView roundedImageView;

        public ViewHolder(View itemView) {
            super(itemView);
            roundedImageView = itemView.findViewById(R.id.item_img);
        }
    }
    public void getSavings() {
        OkGo.<String>post(BaseHttp.depositcard_data)
                .headers("token",PreferencesUtils.getString(getActivity(),"token"))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            JSONObject obj=new JSONObject(response.body());
                            savings = obj.getString("depositcards");
                            if (savings.equals("false")){
                                PreferencesUtils.putString(getActivity(),"savings","false");
                            }else {
                                if (savings.equals("")){
                                    PreferencesUtils.putString(getActivity(),"savings","false");
                                }else {
                                    PreferencesUtils.putString(getActivity(),"savings","true");
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    //绑定储蓄卡对话框
    private void deposit_card() {
        final NormalDialog dialog = new NormalDialog(getContext());
        dialog.content("没有绑定储蓄卡，无法进行此业务")
                .style(NormalDialog.STYLE_TWO)
                .titleTextSize(23)
                .showAnim(bas_in)
                .dismissAnim(bas_out)
                .show();
        dialog.setOnBtnClickL(
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        dialog.dismiss();
                    }
                },
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        Intent intent = new Intent(getActivity(), CreditCardActivity.class);
                        startActivity(intent);
                        dialog.dismiss();
                    }
                });
    }

    //绑定信用卡对话框
    private void creditad_dialog() {
        final NormalDialog dialog = new NormalDialog(getContext());
        dialog.content("没有绑定信用卡，无法进行此业务")
                .style(NormalDialog.STYLE_TWO)
                .titleTextSize(23)
                .showAnim(bas_in)
                .dismissAnim(bas_out)
                .show();
        dialog.setOnBtnClickL(
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        dialog.dismiss();
                    }
                },
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        Intent intent = new Intent(getActivity(), CreditAddition1Activity.class);
                        startActivity(intent);
                        dialog.dismiss();
                    }
                });
    }

    //微信分享
    private void sharewx(int flag) {
        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = "http://web.zgzngj.com";
        WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = "诸葛智能管家";
        msg.description = "我发现一款超级好玩的APP,赶快下载抢红包";
        Bitmap thumb = BitmapFactory.decodeResource(getResources(), R.mipmap.logo);
        msg.setThumbImage(thumb);
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = String.valueOf(System.currentTimeMillis());
        req.message = msg;
        req.scene = flag == 0 ? SendMessageToWX.Req.WXSceneSession : SendMessageToWX.Req.WXSceneTimeline;
        wxApi.sendReq(req);
    }

    //走马灯
    private void walktext() {
        OkGo.<String>post(BaseHttp.msgCounts_Newsnotice)
                .tag(this)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        WalkTextBean walkTextBean= (WalkTextBean) new DataParse().getBean(response.body(),WalkTextBean.class,0);
                        datas=walkTextBean.getMsgRecive();
                        marquessFactory.setData(datas);
                        walktext.setMarqueeFactory(marquessFactory);
                        walktext.startFlipping();

                    }
                });

    }

    //客服对话框
    private void phone_dialog() {
        BounceTopEnter mBasIn =  new BounceTopEnter();
        SlideBottomExit mBasOut = new SlideBottomExit();
        final MaterialDialog dialog=new MaterialDialog(getActivity());
        dialog.btnNum(1)
                .content("客服热线：400-165-0899")
                .btnText("确定")
                .showAnim(mBasIn)
                .dismissAnim(mBasOut)
                .show();
        dialog.setOnBtnClickL(new OnBtnClickL() {
            @Override
            public void onBtnClick() {
                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"+"4001650899"));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                dialog.dismiss();
            }
        });
    }

    /**
     * 可以使用startAutoPlay和stopAutoPlay来控制自动轮播
     */
    @Override
    public void onStart() {
        super.onStart();
        home_banner.startAutoPlay();
    }

    @Override
    public void onStop() {
        super.onStop();
        home_banner.stopAutoPlay();
    }
}

